package com.lsf.studentmanagerup.servlet;

import com.lsf.studentmanagerup.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李树飞
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //获取用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //使用管理员用户服务层实现登录
        UserService userService = new UserService();
        boolean b = userService.userLoginService(username, password);
        if (b) {
            System.out.println("登录成功");
            //若登陆成功，则设置session存储对象
            request.getSession().setAttribute("user",username);

            //添加Cookie，设置期限为一周，响应到信息中，7*24*60*60=604800
            Cookie cookie = new Cookie("user", username);
            cookie.setMaxAge(604800);
            response.addCookie(cookie);

            response.sendRedirect("main");
        }else {
            System.out.println("登录失败");
            //转发回登录页面，范围是当前请求
            request.setAttribute("error", "登录失败,用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
